package com.isyscore.os.metadata.kettle.vis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.isyscore.os.metadata.enums.KettleDataFlowNodeGroupType;
import com.isyscore.os.metadata.enums.KettleDataFlowNodeType;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 数据分组
 */
@ApiModel("分组组件")
@Data
@EqualsAndHashCode(callSuper = false)
public class GroupByNode extends  VisNode {
    @ApiModelProperty("分组字段")
    @NotEmpty(message = "分组字段不能为空")
    @Valid
    private List<String> groupFiled;
    @ApiModelProperty("度量列表")
    @NotEmpty(message = "度量列表不能为空")
    @Valid
    private List<GroupByMeasure> measures;

    @ApiModelProperty("是否内存分组")
    @NotNull(message = "是否内存分组不能为空")
    private boolean isInMemory;

    @Override
    public void valueOf(Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject(params);
        this.groupFiled = JSONArray.parseArray(jsonObject.getJSONArray("groupFiled").toString(), String.class);
        this.isInMemory = "yes".equals(jsonObject.getString("isInMemory"))?true:false;
        this.measures = Optional.ofNullable(jsonObject.getJSONArray("measures")).orElse(new JSONArray()).stream().map(o ->
                JSON.parseObject(JSON.toJSONString(o), GroupByMeasure.class)).collect(Collectors.toList());
        setId(jsonObject.getString("id"));
        setNodeName(jsonObject.getString("nodeName"));
    }
    @Override
    public KettleDataFlowNodeGroupType getGroupType() {
        return KettleDataFlowNodeGroupType.TRANS;
    }

    @Override
    public KettleDataFlowNodeType getNodeType(){
        return KettleDataFlowNodeType.GroupBy;
    }
}
